<template>
  <div>
    <AForm :model="searchFrom" class="erp-search-form">
      <ARow class="grid-demo" :gutter="10">
        <ACol :span="6">
          <AFormItem hide-label content-class="">
            <AInput v-model="searchFrom.processName" placeholder="工序名称" />
          </AFormItem>
        </ACol>
      </ARow>
    </AForm>
    <ACard>
      <div class="erp-mb-10 w100 erp-search-btn-box">
        <ASpace>
          <AButton type="primary" @click="onSearch">
            <template #icon>
              <icon-search />
            </template>
          </AButton>
          <ATooltip content="清空筛选项" position="top">
            <AButton type="dashed" @click="onReset">
              <template #icon>
                <icon-refresh />
              </template>
            </AButton>
          </ATooltip>
          <AButton v-if="isAuth([1, 2])" type="outline" @click="openEdit('新增')">新增</AButton>
          <!-- <tableImp
            imp-url="/produce/erpCustomerImport"
            :file-temp="() => onExport('template')"
          ></tableImp> -->
          <ATooltip
            v-if="isAuth([1, 2])"
            :disabled="!isEmpty(selectedRowKeys)"
            content="请选择数据"
          >
            <AButton status="danger" @click="batchDel()">批量删除</AButton>
          </ATooltip>
        </ASpace>
        <ASpace>
          <AButton type="primary" @click="onExport('table')">导出</AButton>
        </ASpace>
      </div>
      <ATable
        ref="tableRef"
        v-model:selected-keys="selectedRowKeys"
        :pagination="false"
        :data="tableData"
        :bordered="{ cell: true }"
        :row-selection="{ showCheckedAll: true, type: 'checkbox' }"
        :span-method="spanMethod"
        span-all
        column-resizable
        row-key="processId"
        size="small"
      >
        <template #columns>
          <ATableColumn title="工序名称" data-index="processName" :width="100"></ATableColumn>
          <ATableColumn title="机长" data-index="mainDirectorName" :width="100"></ATableColumn>
          <ATableColumn title="辅助人员" data-index="deputyDirectorNameList" :width="100">
            <template #cell="{ record }">
              <div v-if="record.deputyDirectorNameList">
                {{ record.deputyDirectorNameList.join(',') }}
              </div>
            </template>
          </ATableColumn>
          <ATableColumn v-if="isAuth([1, 2])" title="操作" :width="150" fixed="right">
            <template #cell="{ record }">
              <ASpace>
                <AButton type="primary" size="mini" @click="rowEvent(record, 'edit')">
                  修改
                </AButton>
                <AButton status="danger" size="mini" @click="rowEvent(record, 'del')">
                  删除
                </AButton>
              </ASpace>
            </template>
          </ATableColumn>
        </template>
      </ATable>
      <div class="arco-table-pagination">
        <APagination
          :total="pageParam.totalCount"
          :page-size="pageParam.pageSize"
          show-total
          @change="(page: number) => tableEvent('page-change', page)"
        />
      </div>
    </ACard>
    <EditPopupForm
      v-model:visible="editModal"
      :title="editModalTitle"
      :check-data="rowData"
      @reload="
        () => {
          getTableData()
          clearTableSelect()
        }
      "
    ></EditPopupForm>
  </div>
</template>

<script lang="ts" setup>
import EditPopupForm from './editPopupForm.vue'
import { Message, Modal, TableInstance } from '@arco-design/web-vue'
import { isAuth } from '@renderer/utils/auth'
import {
  batchDelProcess,
  delProcess,
  getProcessAllList,
  getProcessPageList,
  ProcessListSearch,
  ProcessResItem
} from '@renderer/api/productionDep'
import { isEmpty } from 'lodash-es'
// import tableImp from '@renderer/components/table/import.vue'
const searchFrom = ref<ProcessListSearch>({})
const editModal = ref(false)
const editModalTitle = ref('新增')
const tableData = ref<ProcessResItem[]>([])
const pageParam = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0
})
const selectedRowKeys = ref<string[]>([])
const tableRef = ref<TableInstance>()

onMounted(() => {
  getTableData()
})

function batchDel() {
  batchDelProcess({ idList: selectedRowKeys.value }).then(() => {
    Message.success('删除成功')
    onSearch()
    clearTableSelect()
  })
}

async function getTableData() {
  const res = await getProcessPageList({ ...searchFrom.value, ...pageParam })
  tableData.value = res.data.list
  pageParam.totalCount = res.data.totalCount!
}

const spanMethod = ({ record, columnIndex }) => {
  if (columnIndex < 3) {
    if (record.span) {
      return {
        colspan: 1,
        rowspan: record.span
      }
    }
  }
}

function clearTableSelect() {
  tableRef.value?.selectAll(false)
  selectedRowKeys.value = []
}

const onSearch = () => {
  pageParam.currentPage = 1
  getTableData()
}

function onReset() {
  searchFrom.value = {}
  pageParam.currentPage = 1
  pageParam.pageSize = 20
  getTableData()
}

function tableEvent(type: 'page-change', param: any) {
  switch (type) {
    case 'page-change':
      pageParam.currentPage = param
      getTableData()
      break

    default:
      break
  }
}

function openEdit(title: string) {
  rowData.value = {}
  editModalTitle.value = title
  editModal.value = true
}

const rowData = ref({})

function rowEvent(row: ProcessResItem, type: 'del' | 'copy' | 'edit' | 'print') {
  switch (type) {
    case 'del':
      Modal.warning({
        title: '警告',
        content: '当前数据删除后不可恢复，是否继续？',
        okText: '确认',
        cancelText: '取消',
        simple: false,
        hideCancel: false,
        maskClosable: false,
        closable: false,
        onOk: () => {
          delProcess({ processId: row.processId! }).then(() => {
            Message.success('删除成功')
            getTableData()
          })
        },
        onCancel: () => {}
      })
      break
    case 'copy':
      rowData.value = row
      editModalTitle.value = '新增'
      editModal.value = true
      break
    case 'edit':
      rowData.value = row
      editModalTitle.value = '修改'
      editModal.value = true
      break

    default:
      break
  }
}

async function onExport(type: 'table' | 'template') {
  let fileTitle: string
  const headerData = [
    { title: '工序名称', value: 'processName', width: 180 },
    { title: '机长', value: 'mainDirectorName', width: 180 },
    { title: '辅助人员', value: 'deputyDirectorNames', width: 180 }
  ]
  let excelData: ProcessResItem[] = []
  switch (type) {
    case 'table':
      {
        fileTitle = '工序数据'
        headerData.unshift({ title: '序号', value: 'index', width: 80 })
        const res = await getProcessAllList(searchFrom.value)
        excelData = res.data.list.map((item, index) => {
          item.index = index + 1
          item.deputyDirectorNames = item.deputyDirectorNameList?.join(',')
          return item
        })
      }
      break
    case 'template':
      fileTitle = '生产计划导入模板'
      excelData = [
        {
          processName: '包装',
          mainDirectorId: '',
          deputyDirectorIdList: [],
          mainDirectorName: '',
          deputyDirectorNameList: [],
          deputyDirectorNames: ''
        }
      ]
      break
    default:
      break
  }
  import('@renderer/utils/vendor').then((excel) => {
    excel.exportExcel(excelData, headerData, fileTitle)
  })
}
</script>
<style lang="less" scoped>
.erp-search-btn-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
